import { successResponse, errorResponse } from 'server/utils/response'
import { pool } from 'server/database/config'

export default defineEventHandler(async (event) => {
  try {
    // 获取首页统计数据
    const [statsResult]: any = await pool.execute(`
      SELECT 
        COUNT(*) as total_projects,
        SUM(CASE WHEN status = 'published' THEN 1 ELSE 0 END) as published_projects,
        SUM(CASE WHEN status = 'draft' THEN 1 ELSE 0 END) as draft_projects,
        SUM(CASE WHEN status = 'archived' THEN 1 ELSE 0 END) as archived_projects,
        SUM(view_count) as total_views,
        SUM(like_count) as total_likes,
        COUNT(DISTINCT category) as total_categories
      FROM projects
    `)

    const [categoriesResult]: any = await pool.execute(`
      SELECT COUNT(*) as total_categories FROM categories WHERE status = 'active'
    `)

    const [tagsResult]: any = await pool.execute(`
      SELECT COUNT(*) as total_tags FROM tags
    `)

    const stats = statsResult[0]
    const categories = categoriesResult[0]
    const tags = tagsResult[0]

    const response = {
      totalPosts: parseInt(stats.total_projects) || 0,
      totalCategories: parseInt(categories.total_categories) || 0,
      totalTags: parseInt(tags.total_tags) || 0,
      totalUsers: 1,
      publishedPosts: parseInt(stats.published_projects) || 0,
      draftPosts: parseInt(stats.draft_projects) || 0,
      activeUsers: 1,
      posts: {
        total: parseInt(stats.total_projects) || 0,
        thisMonth: 0
      },
      comments: {
        total: 0,
        pending: 0
      },
      views: {
        total: parseInt(stats.total_views) || 0,
        today: 0,
        weekly: [0, 0, 0, 0, 0, 0, 0]
      },
      users: {
        total: 1,
        thisMonth: 0
      }
    }

    return successResponse(response, '获取统计数据成功')
  } catch (error) {
    console.error('获取统计数据失败:', error)
    return errorResponse('获取统计数据失败', error instanceof Error ? error.message : '未知错误')
  }
})